// app/controller/upload.js
const path = require('path');
const sendToWormhole = require('stream-wormhole');
const Controller = require('egg').Controller;
const fs = require("fs");

class SpiderController extends Controller {
  async upload() {
    const ctx = this.ctx;
    // file not exists will response 400 error
    const stream = await ctx.getFileStream();
    console.log("path=======================")
    console.log(path)
    console.log(path.basename)
    const name = 'egg-multipart-test/' + path.basename(stream.filename);
    let result;
    console.log("result")
    console.log(result)
    try {
      // process file or upload to cloud storage
      result = await ctx.oss.put(name, stream);
      console.log("try--------------")
      console.log(result)
    } catch (err) {
      // must consume the stream, otherwise browser will be stuck.
      await sendToWormhole(stream);
      throw err;
    }
 
    ctx.body = {
      url: result.url,
      // process form fields by `stream.fields`
      fields: stream.fields,
    };
  }

  async uploadSaveLocal(){
    const ctx = this.ctx;
    let result = null;

    let baseDir = this.config.baseDir;
    const imgSrc = this.config.imgSrc;

    let target = null;
    let stream = null;
    let filename = null;
    // console.log(this.config.baseDir)
    // console.log(ctx.config.baseDir)
    try{
      stream = await ctx.getFileStream();
      console.log('stream.filename')
      console.log(stream.mime)
      const fileType = stream.mime.replace("image/","")
       filename = Date.now() + '' + Number.parseInt(Math.random() * 10000)+"."+fileType
      target  = path.join(baseDir, `app/static/upload/img/${filename}`);
      result = await new Promise((resolve, reject) => {
          const remoteFileStream = fs.createWriteStream(target);
          stream.pipe(remoteFileStream);
          let errFlag;
          remoteFileStream.on('error', err => {
              errFlag = true;
              sendToWormhole(stream);
              remoteFileStream.destroy();
              reject(err);
          });
          
          remoteFileStream.on('finish', async () => {
              if (errFlag) return;
              console.log(stream.fields.name)
              resolve({name: stream.fields.name });
          });
        });
    }catch(e){
      ctx.app.logger.error(e);
      await sendToWormhole(stream);
      throw err;
    }
   
    ctx.body = {
      url: imgSrc+filename,
      // process form fields by `stream.fields
    };
  }
  
 
  async uploadNotRequiredFile() {
    const ctx = this.ctx;
    // file not required
    const stream = await ctx.getFileStream({ requireFile: false });
    let result;
    if (stream.filename) {
      const name = 'egg-multipart-test/' + path.basename(stream.filename);
      try {
        // process file or upload to cloud storage
        result = await ctx.oss.put(name, stream);
      } catch (err) {
        // must consume the stream, otherwise browser will be stuck.
        await sendToWormhole(stream);
        throw err;
      }
    } else {
      // must consume the empty stream
      await sendToWormhole(stream);
    }
 
    ctx.body = {
      url: result && result.url,
      // process form fields by `stream.fields`
      fields: stream.fields,
    };
  }
};

module.exports = SpiderController